package com.wyzt.order.service;

import com.wyzt.auth.entiy.UserInfo;
import com.wyzt.common.dto.CartDTO;
import com.wyzt.common.enums.ExceptionEnum;
import com.wyzt.common.exception.WyztException;
import com.wyzt.common.utils.IdWorker;
import com.wyzt.item.pojo.Sku;
import com.wyzt.order.client.GoodsClient;
import com.wyzt.order.dto.OrderDTO;
import com.wyzt.order.enums.OrderStatusEnum;
import com.wyzt.order.interceptor.UserInterceptor;
import com.wyzt.order.mapper.OrderDetailMapper;
import com.wyzt.order.mapper.OrderMapper;
import com.wyzt.order.mapper.OrderStatusMapper;
import com.wyzt.order.pojo.Order;
import com.wyzt.order.pojo.OrderDetail;
import com.wyzt.order.pojo.OrderStatus;
import com.wyzt.order.utils.PayHelper;
import com.wyzt.order.utils.PayState;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderStatusMapper orderStatusMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private IdWorker idWorker;
    @Autowired
    private PayHelper payHelper;


    @Transactional
    public Long createOrder(OrderDTO orderDTO) {
        // 1. 新增订单
        Order order = new Order();
        // 1.1 订单编号，基本信息
        long orderId = idWorker.nextId();
        order.setOrderId(orderId);
        order.setCreateTime(new Date());
        order.setPaymentType(orderDTO.getPaymentType());
        // 1.2 用户信息
        UserInfo userInfo = UserInterceptor.getUser();
        order.setUserId(userInfo.getId());
        order.setBuyerNick(userInfo.getUsername());
        order.setBuyerRate(false);

        // 1.3 收货人地址
        //todo 获取收货人信息
//        order.setReceiver();
//        order.setReceiverCity();
//        order.setReceiverAddress();
//        order.setReceiverDistrict();
//        order.setReceiverMobile();
//        order.setReceiverState();
//        order.setReceiverZip();
        // 1.4 金额
        //把cartDTO转换为map K:skuId V:num
        Map<Long, Integer> numMap = orderDTO.getCarts()
                .stream()
                .collect(Collectors.toMap(CartDTO::getSkuId, CartDTO::getNum));
        Set<Long> ids = numMap.keySet();
        List<Sku> skus = goodsClient.querySkuBySpuIds(new ArrayList<>(ids));

        //准备orderDetail集合
        List<OrderDetail> details = new ArrayList<>();
        long totalPay = 0L;
        for (Sku sku : skus) {
            //计算商品总价
            totalPay += sku.getPrice() * numMap.get(sku.getId());

            //封装orderDetail
            OrderDetail detail = new OrderDetail();
            detail.setImage(StringUtils.substringBefore(sku.getImages(), ","));
            detail.setNum(numMap.get(sku.getId()));
            detail.setOrderId(orderId);
            detail.setPrice(sku.getPrice());
            detail.setSkuId(sku.getId());
            detail.setTitle(sku.getTitle());
            details.add(detail);
        }

        order.setTotalPay(totalPay);
        //实付金额：总金额+邮费-优惠
        order.setActualPay(totalPay + order.getPostFee() - 0);
        // 1.5 写入数据库
        int count = orderMapper.insertSelective(order);
        if (count != 1) {
            log.error("[创建订单]创建订单失败，orderId：{}", orderId);
            throw new WyztException(ExceptionEnum.CREATE_ORDER_ERROR);
        }

        // 2. 新增订单详情
        count = orderDetailMapper.insertList(details);
        if (count != details.size()) {
            log.error("[创建订单]创建订单失败，orderId：{}", orderId);
            throw new WyztException(ExceptionEnum.CREATE_ORDER_ERROR);
        }
        // 3. 新增订单状态
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setCreateTime(order.getCreateTime());
        orderStatus.setOrderId(orderId);
        orderStatus.setStatus(OrderStatusEnum.UN_PAY.value());
        count = orderStatusMapper.insertSelective(orderStatus);
        if (count != details.size()) {
            log.error("[创建订单]创建订单失败，orderId：{}", orderId);
            throw new WyztException(ExceptionEnum.CREATE_ORDER_ERROR);
        }

        // 4. 减库存
        goodsClient.decreaseStock(orderDTO.getCarts());

        return orderId;
    }

    public Order queryOrderById(Long id) {

        Order order = orderMapper.selectByPrimaryKey(id);
        if (order == null) {
            throw new WyztException(ExceptionEnum.ORDER_NOT_FOUND);
        }
        //查询订单详情
        OrderDetail detail = new OrderDetail();
        detail.setOrderId(id);
        List<OrderDetail> orderDetails = orderDetailMapper.select(detail);
        if (CollectionUtils.isEmpty(orderDetails)) {
            throw new WyztException(ExceptionEnum.ORDER_DETAIL_NOT_FOUND);
        }
        order.setOrderDetails(orderDetails);
        //查询订单状态
        OrderStatus orderStatus = orderStatusMapper.selectByPrimaryKey(id);
        if (orderStatus == null) {
            throw new WyztException(ExceptionEnum.ORDER_STATUS_NOT_FOUND);
        }
        order.setStatus(orderStatus);
        return order;
    }

    public String createPayUrl(Long id) {
        //查询订单，获取订单总金额
        Order order = queryOrderById(id);
        //判断订单状态
        Integer status = order.getStatus().getStatus();
        if (status != OrderStatusEnum.UN_PAY.value()) {
            //订单状态异常
            throw new WyztException(ExceptionEnum.ORDER_STATUS_ERROR);
        }

        //支付金额
        Long totalPay = order.getActualPay();
        //商品描述
        String desc = order.getOrderDetails().get(0).getTitle();
        return payHelper.createPayUrl(id, totalPay, desc);
    }

    public void handleNotify(Map<String, String> result) {
        //处理支付回调
        //数据校验
        payHelper.isSuccess(result);
        //签名验证
        payHelper.isValidSign(result);
        //验证金额是否一致
        String totalFeeStr = result.get("total_fee");
        String tradeNoStr = result.get("out_trade_no");
        if (StringUtils.isEmpty(totalFeeStr)) {
            throw new WyztException(ExceptionEnum.INVALID_SIGN_PARAM);
        }
        if (StringUtils.isEmpty(tradeNoStr)) {
            throw new WyztException(ExceptionEnum.INVALID_SIGN_PARAM);
        }
        //获取结果中的金额
        Long totalFee = Long.valueOf(totalFeeStr);
        //获取订单金额
        Long orderId = Long.valueOf(tradeNoStr);
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (!totalFee.equals(order.getActualPay())) {
            throw new WyztException(ExceptionEnum.INVALID_SIGN_PARAM);
        }

        //修改订单状态
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setStatus(OrderStatusEnum.PAYED.value());
        orderStatus.setOrderId(orderId);
        orderStatus.setPaymentTime(new Date());
        int count = orderStatusMapper.updateByPrimaryKeySelective(orderStatus);
        if (count != 1) {
            throw new WyztException(ExceptionEnum.UPDATE_STATUS_ERROR);
        }
        log.info("[支付回调]，订单支付成功！订单编号：{}", orderId);
    }

    public PayState queryOrderState(Long orderId) {
        //查询订单状态
        OrderStatus OrderStatus = orderStatusMapper.selectByPrimaryKey(orderId);
        Integer status = OrderStatus.getStatus();
        //判断是否支付
        if (status != OrderStatusEnum.UN_PAY.value()) {
            //如果以支付，则真的完成了支付
            return PayState.SUCCESS;
        }
        //如果未支付，则不一定是未支付，必须去微信查询支付状态
        return payHelper.queryOrder(orderId);
    }
}
